package com.topera.eduservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.topera.commonutils.R;
import com.topera.eduservice.client.VodClient;
import com.topera.eduservice.entity.EduVideo;
import com.topera.eduservice.service.EduVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author puzhenjiang
 * @since 2020-05-18
 */
@RestController
@RequestMapping("/eduservice/video")
@CrossOrigin
public class EduVideoController {

    @Autowired
    private EduVideoService videoService;

    @Autowired
    private VodClient vodClient;//用于调用vod模块的接口

    /**
     * 根据章节id查询小姐信息 用于约束章节是否能都被删除
     * @param chapterId
     * @return
     */
    @GetMapping("getVideoByChapterId/{chapterId}")
    public R getVideoByChapterId(@PathVariable String chapterId){
        QueryWrapper<EduVideo> wrapper = new QueryWrapper();
        wrapper.eq("chapter_id",chapterId);
        int result = videoService.count(wrapper);
        return R.ok().data("result",result);
    }

    /**
     * 保存小节信息
     * @param video
     * @return
     */
    @PostMapping("addVideo")
    public R addVideo(@RequestBody EduVideo video){
        videoService.save(video);
        return R.ok();
    }

    /**
     * 根据id获取小节信息
     * @param id
     * @return
     */
    @GetMapping("getVideoById/{id}")
    public R getVideoById(@PathVariable String id){
        EduVideo video = videoService.getById(id);
        return R.ok().data("video",video);
    }

    /**
     * 更新小节信息
     * @param video
     * @return
     */
    @PostMapping("updateVideo")
    public R updateVideo(@RequestBody EduVideo video){
        videoService.updateById(video);
        return R.ok();
    }

    /**
     * 删除小节信息
     * @param id
     * @return
     */
    @DeleteMapping("deleteVideo/{id}")
    public R deleteVideo(@PathVariable String id){

        /**
         * 删除小节的时候 同时应该将视频进行删除
         * 此时 要通过服务之间的调用进行删除
         *
         * */

        //根据id获取小节信息
        EduVideo video =  videoService.getById(id);
        if(video!=null && video.getVideoSourceId()!=null){
            //删除视频
            vodClient.deleteVideo(video.getVideoSourceId());
        }

        videoService.removeById(id);


        return R.ok();
    }
}

